﻿using System;
using System.Collections.Generic;
using System.Web;
using WAD.WEB.AppCode;
using WAD.Model;
using WAD.DAL;
using System.Text;
using WAD.BLL;
using GL.Tools;
namespace WAD.WEB.Client.Ajax
{
    /// <summary>
    /// 发财：广告主文章接口
    /// </summary>
    public class FC_Article : AjaxBase
    {
        public override void AjaxMethodDispatch(String identity)
        {
            switch (identity)
            {
                case "add": this.Add(); break;
                case "addarticle": this.AddArticle(); break;
                case "getlist": this.GetList(); break;
                case "getsetting": this.GetSetting(); break;
                case "setting": this.Setting(); break;
                case "delete": this.Delete(); break;
                case "getlist_shared": this.GetList_Shared(); break;
                case "getlist_top": this.GetList_Top(); break;
                case "get": this.Get(); break;
            }
        }
        #region 广告主

        /// <summary>
        /// 广告主: 添加文章
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Add()
        {
            int article_id = Parse.Int("article_id", 0);    //发布栏目的文章ID
            MFCArticle m = new MFCArticle();
            m.user_id = Parse.Int("user_id", 0);
            m.state = 0;
            m.date = DateTime.Now;

            if (m.user_id < 1)
                ParamError();

            if (article_id > 0)
            {
                //原创文章，则从文章中获取标题、LOGO、简介
                Dictionary<string, object> model = DaoArticle.GetDetail(article_id);
                if (model == null)
                    JsonResult(1, "找不到文章");

                m.title = Convert.ToString(model["title"]);
                m.logo = Convert.ToString(model["logo"]);
                m.url = string.Format("{0}/client/item.aspx?article_id={1}", WJXConfig.Path.URL, article_id);
                m.content = QD.Utils.StringUtils.RemoveHtml(Convert.ToString(model["content"])).Replace("\r", "").Replace("\n", "").Trim();
                if (m.content.Length > 50)
                    m.content = m.content.Substring(0, 50);
            }
            else
            {
                //外部链接，从参数中获取标题、LOGO、简介
                m.title = Context.Server.UrlDecode(Parse.String("url_title", ""));
                m.logo = Context.Server.UrlDecode(Parse.String("url_logo", ""));

                //微信图片
                if (m.logo.IndexOf("//mmbiz.qpic.cn") != -1)
                {
                    string savaPath;    //格式：磁盘/Upload/Image/2015/02/28/20160301141712B4FyjS.jpg
                    if (!string.IsNullOrEmpty(WJXConfig.Path.UPLOAD_DIR))
                        savaPath = string.Format("{0}{1}{2}/{3}/{4}{5}{6}", WJXConfig.Path.UPLOAD_DIR, WJXConfig.Path.IMAGE, DateTime.Now.ToString("yyyy"), DateTime.Now.ToString("MM"), DateTime.Now.ToString("yyyyMMddHHmmss"), StringHelper.Random(6), ".jpg");
                    else
                        savaPath = string.Format("{0}{1}/{2}/{3}{4}{5}", HttpContext.Current.Server.MapPath(WJXConfig.Path.IMAGE), DateTime.Now.ToString("yyyy"), DateTime.Now.ToString("MM"), DateTime.Now.ToString("yyyyMMddHHmmss"), StringHelper.Random(6), ".jpg");

                    //微信图片下载到本地
                    if (HttpTool.SavaFile(m.logo, savaPath))
                    {
                        if (!string.IsNullOrEmpty(WJXConfig.Path.UPLOAD_DIR))
                            m.logo = savaPath.Substring(savaPath.IndexOf(WJXConfig.Path.UPLOAD_DIR) + WJXConfig.Path.UPLOAD_DIR.Length);    //自定义上传目录
                        else
                            m.logo = savaPath.Substring(savaPath.IndexOf(Context.Server.MapPath(WJXConfig.Path.IMAGE)) + WJXConfig.Path.IMAGE.Length);//IIS目录
                    }
                }

                m.url = Context.Server.UrlDecode(Parse.String("url", ""));
                m.content = m.title;
            }

            int id = DAOFCArticle.Add(m);
            if (id > 0)
                JsonResult(0, "成功", id);
            Fail();
        }

        /// <summary>
        /// 发布新的原创广告
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void AddArticle()
        {
            IsLogin();
            MArticle m = new MArticle();
            m.title = Parse.String("title");//标题
            m.logo = Parse.String("logo");//标题logo
            m.content = HttpUtility.UrlDecode(Parse.String("content", ""));
            m.user_id = UserId;
            m.key_word = Parse.String("key_word");//标题logo
            m.is_recommend = Parse.Boolean("is_recommend", true);//是否允许推荐

            //验证
            if (String.IsNullOrEmpty(m.title) || String.IsNullOrEmpty(m.content) || String.IsNullOrEmpty(m.logo))
            {
                ParamError();
            }

            //关键词为空时 赋值为标题值
            if (String.IsNullOrEmpty(m.key_word))
                m.key_word = m.title;

            int id = 0;
            m.id = DaoArticle.Add(m, true);     //添加原创文章
            if (m.id > 0)
            {
                id = DAOFCArticle.Add(GetModel(m)); //添加广告
                JsonResult(0, "成功", id);
            }

            Fail();
        }

        MFCArticle GetModel(MArticle m)
        {
            MFCArticle model = new MFCArticle();
            model.user_id = Parse.Int("user_id", 0);
            model.state = 0;
            model.date = DateTime.Now;
            model.title = Convert.ToString(m.title);
            model.logo = Convert.ToString(m.logo);
            model.url = string.Format("{0}/client/item.aspx?article_id={1}", WJXConfig.Path.URL, m.id);
            model.content = QD.Utils.StringUtils.RemoveHtml(Convert.ToString(m.content)).Replace("\r", "").Replace("\n", "").Trim();
            if (m.content.Length > 50)
                m.content = m.content.Substring(0, 50);
            return model;
        }


        /// <summary>
        /// 广告主: 获取广告列表
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetList()
        {
            IsLogin();
            int user_id = Parse.Int("user_id", 0);
            int state = Parse.Int("state", -1);
            int pageIndex = Parse.Int("page_index", 1);//当前页
            String keyWord = Parse.String("key_word");//搜索的关键词
            StringBuilder sb = new StringBuilder();
            sb.Append("state<2 and user_id=" + user_id);
            if (!string.IsNullOrEmpty(keyWord))
            {
                keyWord = QD.WX.Utill.Util.FilterSql(keyWord);
                if (!string.IsNullOrEmpty(keyWord))
                    sb.AppendFormat(" and (title like '%{0}%' OR content like '%{0}%')", keyWord);
            }
            if (state > -1)
                sb.Append(" and state=" + state);
            PageData pg = DAOFCArticle.GetListPage("id,title,logo,state,op_total,op_price,op_remainder,op_endtime,date", "id desc", pageIndex, 20, sb.ToString(), "fc_article");

            if (pg.itemCount == 0)
                DataEmpty();
            Success(pg);
        }

        /// <summary>
        /// 广告主
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetSetting()
        {
            IsLogin();
            int user_id = Parse.Int("user_id", 0);
            int id = Parse.Int("id", 0);
            if (id < 1) ParamError();
            Dictionary<string, object> model = DAOFCArticle.Get("fc_article", "id=" + id, "title,op_total,op_price,op_plat,op_starttime,op_endtime,op_area1,op_area2,op_area3,state");
            if (model != null)
                Success(model);
            else
                DataEmpty();
        }

        /// <summary>
        /// 广告主： 广告设置
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Setting()
        {
            IsLogin();
            MFCArticle m = new MFCArticle()
            {
                id = Parse.Int("id", 0),
                op_total = Parse.Int("op_total", 0),
                op_remainder = Parse.Int("op_total", 0),
                op_starttime = Parse.Date("op_starttime", DateTime.Now),
                op_endtime = Parse.Date("op_endtime", DateTime.Now.AddYears(1)),
                op_price = Parse.Decimal("op_price", 0),
                op_plat = Parse.Int("op_plat", 1),
                op_area1 = Parse.String("op_area1", "").Replace("请选择", "").Replace("null", ""),
                op_area2 = Parse.String("op_area2", "").Replace("请选择", "").Replace("null", ""),
                op_area3 = Parse.String("op_area3", "").Replace("请选择", "").Replace("null", ""),
            };
            if (m.id < 1) ParamError();

            //是否发了很多条
            int count = DAOFCArticle.GetCount("fc_article", "state=1 and user_id=" + userBean.id.Value);
            if (count < 1)
            {
                //第一次添加,允许任意单价
                if (m.op_total < 1)
                    JsonResult(11, "数量必需大于1");
                if (m.op_price < 1)
                    JsonResult(11, "单价不能低于1元");
            }
            else
            {
                if (m.op_total < 100)
                    JsonResult(11, "数量不能小于100");

                if (string.IsNullOrEmpty(m.op_area1))   //未设置区域,单价最低1元,设置了区域，单价最低5元
                {
                    if (m.op_price < 1)
                        JsonResult(11, "单价不能低于1元");
                }
                else
                {
                    if (m.op_price < 5)
                        JsonResult(11, "单价不能低于5元");
                }
            }

            if (DAOFCArticle.Setting(m) > 0)
                Success();
            else
                Fail();
        }

        /// <summary>
        /// 广告主：删除一条广告
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Delete()
        {
            int id = Parse.Int("id", 0);
            if (id < 1) ParamError();
            IsLogin();
            Dictionary<string, object> model = DAOFCArticle.Get("fc_article", "id=" + id.ToString(), "state");
            if (model == null || model["state"] == DBNull.Value)
                Success();
            if (Convert.ToInt32(model["state"]) == 1)
                JsonResult(11, "分享中的广告文章不能删除");

            int count = DAOFCArticle.Delete(id);
            if (count > 0)
                Success();
            Fail();
        }
        #endregion

        #region 分享者
        /// <summary>
        /// 分享主: 获取广告列表
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetList_Shared()
        {
            int user_id = Parse.Int("user_id", 0);
            int pageIndex = Parse.Int("page_index", 1);//当前页

            Dictionary<string, object> setting = DAOFCSetting.Get("fc_setting", "user_id=" + user_id, "wx_name,wx_number,state,area1,area2,area3");

            if (setting == null || setting["area1"] == DBNull.Value)
            {
                UpdateLocation(user_id, Parse.String("area1", ""), Parse.String("area2", ""), Parse.String("area3", ""));
            }

            #region 2.0.2版本注释 2016-03-17

            //if (setting == null)
            //{
            //    JsonResult(10, "请到我的设置中完善资料");
            //}
            //if (setting["wx_name"] == DBNull.Value || string.IsNullOrEmpty(Convert.ToString(setting["wx_name"])))
            //{
            //    JsonResult(11, "请填写微信号");
            //}
            //if (setting["wx_number"] == DBNull.Value || Convert.ToInt32(setting["wx_number"]) < 100)
            //{
            //    JsonResult(11, "您的微信好友不够100人");
            //}

            #endregion

            #region 注释 2016-08-12
            /*
            StringBuilder where = new StringBuilder();
            where.Append("state=1 and op_remainder>0 and op_starttime<getdate() and datediff(dd,getdate(),op_endtime)>-1");
            if (setting != null)
            {
                if (setting["area1"] != DBNull.Value)
                    where.AppendFormat(" and isnull(op_area1,'{0}')='{0}'", setting["area1"]);    //省

                if (setting["area2"] != DBNull.Value)
                    where.AppendFormat(" and isnull(op_area2,'{0}')='{0}'", setting["area2"]);    //市

                if (setting["area3"] != DBNull.Value)
                    where.AppendFormat(" and isnull(op_area3,'{0}')='{0}'", setting["area3"]);    //区
            }
            else
            {
                if (!string.IsNullOrEmpty(Parse.String("area1")))
                    where.AppendFormat(" and isnull(op_area1,'{0}')='{0}'", Parse.String("area1"));    //省
                if (!string.IsNullOrEmpty(Parse.String("area2")))
                    where.AppendFormat(" and isnull(op_area2,'{0}')='{0}'", Parse.String("area2"));    //市
                if (!string.IsNullOrEmpty(Parse.String("area3")))
                    where.AppendFormat(" and isnull(op_area3,'{0}')='{0}'", Parse.String("area3"));    //区
            }

            //只显示未抢的、超过5分钟、的红包          
            where.Append("and id in (select article_id from dbo.fc_shared_money where ");

            where.Append("([state] = 0 and isnull(lock,0)=0) and datediff(mi,isnull(date,'2016-01-01'),getdate())>5");                    //未分享的
            where.AppendFormat("or ([state] = 0 and lock=0 and user_id={0})", user_id);	            //自己占用
            where.AppendFormat("or ([state] = 0 and lock=1 and user_id={0})", user_id);	            //自己未上传图
            where.Append("or ([state] = 0 and lock=0 and datediff(mi,date,getdate())>5)");     //超过5分钟
            //where.Append("or (article_id = 154 and [state] = 0 and lock=1 and datediff(mi,date,getdate())>360)");   //超过5分钟
            where.Append(")");

            //只获取区域内、剩余数>0、未过期的文章，若用户未设置区域，则只能获取全国区域的文章
            PageData pg = DAOFCArticle.GetListPage("id,title,logo,op_area1,op_area2,op_area3,date,'' as picurl,0 as by_user_id,0 as shared_id,0 as money_id", "id desc", pageIndex, 20,
              string.Format(where.ToString(), user_id), "fc_article");

            if (pg.itemCount == 0)
                DataEmpty();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < pg.table.Rows.Count; i++)
                sb.Append("," + pg.table.Rows[i]["id"]);

            if (sb.Length > 1)
            {
                sb.Remove(0, 1);
                //用户已分享的文章
                List<Dictionary<string, object>> list = DAOFCShared.GetListOld(user_id, sb.ToString(), "id,article_id,by_user_id,picurl,money_id,state,date");
                for (int i = 0; i < pg.table.Rows.Count; i++)
                {
                    int article_id = Convert.ToInt32(pg.table.Rows[i]["id"]);
                    for (int j = 0; j < list.Count; j++)
                    {
                        //将分享过的记录，绑定到列表中,客户端判断是否分享过，然后进行跳转
                        if (article_id == Convert.ToInt32(list[j]["article_id"]))
                        {
                            if (!string.IsNullOrEmpty(Convert.ToString(list[j]["picurl"])))
                            {
                                pg.table.Rows.RemoveAt(i);  //分享过的广告，不显示
                                i--;
                                continue;
                            }

                            //临时占用的红包，显示出来允许继续抢
                            if (Convert.ToInt32(list[j]["state"]) != 1)
                            {
                                list[j]["by_user_id"] = 0;
                                list[j]["money_id"] = 0;
                            }
                            else
                            {
                                //分析完成的红包，不显示
                                if (DateTime.Now.Subtract(Convert.ToDateTime(list[j]["date"])).TotalMinutes > 30)
                                {
                                    pg.table.Rows.RemoveAt(i);  //分享过的广告，不显示
                                    i--;
                                    continue;
                                }
                            }

                            //if (DateTime.Now.Subtract(Convert.ToDateTime(list[j]["date"])).TotalMinutes > 30)
                            //{
                            //    pg.table.Rows.RemoveAt(i);  //分享过的广告，不显示
                            //    i--;
                            //    continue;
                            //}

                            pg.table.Rows[i]["shared_id"] = list[j]["id"];
                            pg.table.Rows[i]["picurl"] = list[j]["picurl"];
                            pg.table.Rows[i]["by_user_id"] = list[j]["by_user_id"];
                            pg.table.Rows[i]["money_id"] = list[j]["money_id"];
                        }
                    }
                }
                pg.itemCount = pg.table.Rows.Count;
            }
            */
            #endregion



            StringBuilder where = new StringBuilder();
            //where.Append("state=1 and op_remainder>0 and op_starttime<getdate() and datediff(dd,getdate(),op_endtime)>-1");
            where.Append("state=1 and op_starttime<getdate() and datediff(dd,getdate(),op_endtime)>-1");
            if (setting != null)
            {
                if (setting["area1"] != DBNull.Value)
                    where.AppendFormat(" and isnull(op_area1,'{0}')='{0}'", setting["area1"]);    //省

                if (setting["area2"] != DBNull.Value)
                    where.AppendFormat(" and isnull(op_area2,'{0}')='{0}'", setting["area2"]);    //市

                if (setting["area3"] != DBNull.Value)
                    where.AppendFormat(" and isnull(op_area3,'{0}')='{0}'", setting["area3"]);    //区
            }
            else
            {
                if (!string.IsNullOrEmpty(Parse.String("area1")))
                    where.AppendFormat(" and isnull(op_area1,'{0}')='{0}'", Parse.String("area1"));    //省
                if (!string.IsNullOrEmpty(Parse.String("area2")))
                    where.AppendFormat(" and isnull(op_area2,'{0}')='{0}'", Parse.String("area2"));    //市
                if (!string.IsNullOrEmpty(Parse.String("area3")))
                    where.AppendFormat(" and isnull(op_area3,'{0}')='{0}'", Parse.String("area3"));    //区
            }

            //只获取区域内、剩余数>0、未过期的文章，若用户未设置区域，则只能获取全国区域的文章
            PageData pg = DAOFCArticle.GetListPage("id,title,logo,op_remainder,op_area1,op_area2,op_area3,date,'' as picurl,0 as by_user_id,0 as shared_id,0 as money_id", "id desc", pageIndex, 20,
              string.Format(where.ToString(), user_id), "fc_article");

            if (pg.itemCount == 0)
                DataEmpty();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < pg.table.Rows.Count; i++)
                sb.Append("," + pg.table.Rows[i]["id"]);

            if (sb.Length > 1)
            {
                sb.Remove(0, 1);
                //用户已分享的文章
                List<Dictionary<string, object>> list = DAOFCShared.GetListOld(user_id, sb.ToString(), "id,article_id,by_user_id,picurl,money_id,state,date");


                for (int i = 0; i < list.Count; i++)
                {
                    int article_id = Convert.ToInt32(list[i]["article_id"]);
                    double Minutes = DateTime.Now.Subtract(Convert.ToDateTime(list[i]["date"])).TotalMinutes;   //抢红包的时间

                    //临时占用的红包，显示出来允许继续抢
                    if (Convert.ToInt32(list[i]["state"]) != 1 && Minutes > 30)
                    {
                        list[i]["by_user_id"] = 0;
                        list[i]["money_id"] = 0;
                    }

                    for (int j = 0; j < pg.table.Rows.Count; j++)
                    {
                        //将分享过的记录，绑定到列表中,客户端判断是否分享过，然后进行跳转
                        if (article_id == Convert.ToInt32(pg.table.Rows[j]["id"]))
                        {
                            pg.table.Rows[j]["shared_id"] = list[i]["id"];
                            pg.table.Rows[j]["picurl"] = list[i]["picurl"];
                            pg.table.Rows[j]["by_user_id"] = list[i]["by_user_id"];
                            pg.table.Rows[j]["money_id"] = list[i]["money_id"];
                        }
                    }
                }



                //for (int i = 0; i < pg.table.Rows.Count; i++)
                //{
                //    double Minutes = DateTime.Now.Subtract(Convert.ToDateTime(pg.table.Rows[i]["date"])).TotalMinutes;
                //    int article_id = Convert.ToInt32(pg.table.Rows[i]["id"]);
                //    for (int j = 0; j < list.Count; j++)
                //    {
                //        //将分享过的记录，绑定到列表中,客户端判断是否分享过，然后进行跳转
                //        if (article_id == Convert.ToInt32(list[j]["article_id"]))
                //        {                         
                //            //临时占用的红包，显示出来允许继续抢
                //            if (Convert.ToInt32(list[j]["state"]) != 1 && Minutes > 30)
                //            {
                //                list[j]["by_user_id"] = 0;
                //                list[j]["money_id"] = 0;
                //            }
                //            pg.table.Rows[i]["shared_id"] = list[j]["id"];
                //            pg.table.Rows[i]["picurl"] = list[j]["picurl"];
                //            pg.table.Rows[i]["by_user_id"] = list[j]["by_user_id"];
                //            pg.table.Rows[i]["money_id"] = list[j]["money_id"];
                //        }
                //    }
                //}
            }

            if (pg.itemCount < 1)
                JsonResult(4, "没有红包可以抢");
            JsonResult(0, "成功", pg);
        }

        /// <summary>
        /// 分享主：获取广告前几条(发现页)
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetList_Top()
        {
            int user_id = Parse.Int("user_id", 0);

            StringBuilder where = new StringBuilder();
            where.Append("lock>0");
            if (user_id < 1)
            {
                if (!string.IsNullOrEmpty(Parse.String("area1")))
                    where.AppendFormat(" and isnull(op_area1,'{0}')='{0}'", Parse.String("area1"));    //省
                if (!string.IsNullOrEmpty(Parse.String("area2")))
                    where.AppendFormat(" and isnull(op_area2,'{0}')='{0}'", Parse.String("area2"));    //市
                if (!string.IsNullOrEmpty(Parse.String("area3")))
                    where.AppendFormat(" and isnull(op_area3,'{0}')='{0}'", Parse.String("area3"));    //区
            }
            else
            {
                Dictionary<string, object> setting = DAOFCSetting.Get("fc_setting", "user_id=" + user_id, "wx_name,wx_number,state,area1,area2,area3");

                if (setting == null)
                    DataEmpty();

                if (setting["area1"] != DBNull.Value)
                    where.AppendFormat(" and isnull(op_area1,'{0}')='{0}'", setting["area1"]);    //省

                if (setting["area2"] != DBNull.Value)
                    where.AppendFormat(" and isnull(op_area2,'{0}')='{0}'", setting["area2"]);    //市

                if (setting["area3"] != DBNull.Value)
                    where.AppendFormat(" and isnull(op_area3,'{0}')='{0}'", setting["area3"]);    //区
            }

            PageData pg = DAOFCShared.GetList(5, where.ToString(), "v_fc_article_top", "id,title,op_total,op_remainder,logo,lock,op_area1,op_area2,op_area3,date,'' as picurl,0 as by_user_id,0 as shared_id,0 as money_id", "id desc");
            if (user_id > 0 && pg.table.Rows.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < pg.table.Rows.Count; i++)
                    sb.Append("," + pg.table.Rows[i]["id"]);

                if (sb.Length > 1)
                {
                    sb.Remove(0, 1);
                    List<Dictionary<string, object>> list = DAOFCShared.GetListOld(user_id, sb.ToString(), "article_id,by_user_id");
                    for (int i = 0; i < pg.table.Rows.Count; i++)
                    {
                        int article_id = Convert.ToInt32(pg.table.Rows[i]["id"]);
                        for (int j = 0; j < list.Count; j++)
                        {
                            //将分享过的记录，绑定到列表中,客户端判断是否分享过，然后进行跳转
                            if (article_id == Convert.ToInt32(list[j]["article_id"]))
                            {
                                pg.table.Rows.RemoveAt(i);  //分享过的广告，不显示
                                i--;
                                continue;
                            }
                        }
                    }

                    pg.itemCount = pg.table.Rows.Count;
                }
            }
            JsonResult(0, "", pg);
        }

        void UpdateLocation(int userid, string area1, string area2, string area3)
        {
            DAOFCSetting.UpdateLocation(userid, area1, area2, area3);
        }
        #endregion

        [QD.Web.Ajax.AjaxMethod]
        public void Get()
        {
            IsLogin();
            int id = Parse.Int("id", 0);
            Dictionary<string, object> model = DAOFCArticle.Get("fc_article", "id=" + id, "title,click,content,");
            if (model != null)
                Success(model);
            DataEmpty();
        }
    }
}
